<template>
  <div class="database-management">
    <div class="page-header">
      <h1>数据库管理</h1>
      <p>管理数据库连接、监控性能、执行备份和查询</p>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-cards">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon">
                <el-icon><Database /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ stats.total_connections }}</div>
                <div class="stat-label">数据库连接</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon backup">
                <el-icon><FolderOpened /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ stats.total_backups }}</div>
                <div class="stat-label">备份文件</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon query">
                <el-icon><Search /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ stats.recent_queries }}</div>
                <div class="stat-label">今日查询</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon alert">
                <el-icon><Warning /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ stats.active_alerts }}</div>
                <div class="stat-label">活跃告警</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 功能导航 -->
    <div class="function-nav">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="nav-card" @click="navigateTo('/database/connections')">
            <div class="nav-content">
              <el-icon class="nav-icon"><Connection /></el-icon>
              <h3>连接管理</h3>
              <p>管理数据库连接配置</p>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="nav-card" @click="navigateTo('/database/monitoring')">
            <div class="nav-content">
              <el-icon class="nav-icon"><Monitor /></el-icon>
              <h3>性能监控</h3>
              <p>监控数据库性能指标</p>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="nav-card" @click="navigateTo('/database/backup')">
            <div class="nav-content">
              <el-icon class="nav-icon"><Download /></el-icon>
              <h3>备份管理</h3>
              <p>创建和管理数据库备份</p>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="nav-card" @click="navigateTo('/database/query')">
            <div class="nav-content">
              <el-icon class="nav-icon"><EditPen /></el-icon>
              <h3>SQL查询</h3>
              <p>执行SQL查询和管理</p>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 最近活动 -->
    <div class="recent-activity">
      <el-card>
        <template #header>
          <div class="card-header">
            <span>最近活动</span>
            <el-button type="text" @click="refreshData">刷新</el-button>
          </div>
        </template>
        
        <el-tabs v-model="activeTab">
          <el-tab-pane label="最近查询" name="queries">
            <el-table :data="recentQueries" style="width: 100%">
              <el-table-column prop="connection_name" label="数据库" width="150" />
              <el-table-column prop="query_type" label="类型" width="100" />
              <el-table-column prop="query" label="查询语句" show-overflow-tooltip />
              <el-table-column prop="execution_time" label="执行时间" width="100">
                <template #default="scope">
                  {{ scope.row.execution_time }}ms
                </template>
              </el-table-column>
              <el-table-column prop="status" label="状态" width="100">
                <template #default="scope">
                  <el-tag :type="scope.row.status === 'success' ? 'success' : 'danger'">
                    {{ scope.row.status === 'success' ? '成功' : '失败' }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="executed_at" label="执行时间" width="180" />
            </el-table>
          </el-tab-pane>
          
          <el-tab-pane label="最近备份" name="backups">
            <el-table :data="recentBackups" style="width: 100%">
              <el-table-column prop="connection_name" label="数据库" width="150" />
              <el-table-column prop="name" label="备份名称" />
              <el-table-column prop="backup_type" label="类型" width="100" />
              <el-table-column prop="file_size_mb" label="大小" width="100">
                <template #default="scope">
                  {{ scope.row.file_size_mb }}MB
                </template>
              </el-table-column>
              <el-table-column prop="status" label="状态" width="100">
                <template #default="scope">
                  <el-tag :type="getBackupStatusType(scope.row.status)">
                    {{ getBackupStatusText(scope.row.status) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="created_at" label="创建时间" width="180" />
            </el-table>
          </el-tab-pane>
          
          <el-tab-pane label="活跃告警" name="alerts">
            <el-table :data="activeAlerts" style="width: 100%">
              <el-table-column prop="connection_name" label="数据库" width="150" />
              <el-table-column prop="alert_type" label="告警类型" width="150" />
              <el-table-column prop="severity" label="严重程度" width="100">
                <template #default="scope">
                  <el-tag :type="getAlertSeverityType(scope.row.severity)">
                    {{ getAlertSeverityText(scope.row.severity) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="message" label="告警信息" show-overflow-tooltip />
              <el-table-column prop="created_at" label="创建时间" width="180" />
              <el-table-column label="操作" width="100">
                <template #default="scope">
                  <el-button type="text" size="small" @click="resolveAlert(scope.row)">
                    解决
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import {
  Database, FolderOpened, Search, Warning, Connection,
  Monitor, Download, EditPen
} from '@element-plus/icons-vue'
import api from '@/utils/api'

const router = useRouter()

// 响应式数据
const activeTab = ref('queries')
const stats = reactive({
  total_connections: 0,
  active_connections: 0,
  total_backups: 0,
  recent_backups: 0,
  total_queries: 0,
  recent_queries: 0,
  active_alerts: 0,
  resolved_alerts: 0
})

const recentQueries = ref([])
const recentBackups = ref([])
const activeAlerts = ref([])

// 方法
const navigateTo = (path: string) => {
  router.push(path)
}

const refreshData = async () => {
  await Promise.all([
    fetchStats(),
    fetchRecentQueries(),
    fetchRecentBackups(),
    fetchActiveAlerts()
  ])
  ElMessage.success('数据已刷新')
}

const fetchStats = async () => {
  try {
    const response = await api.get('/database/stats/')
    if (response.data.success) {
      Object.assign(stats, response.data.data)
    }
  } catch (error) {
    console.error('获取统计数据失败:', error)
  }
}

const fetchRecentQueries = async () => {
  try {
    const response = await api.get('/database/query-history/', {
      params: { page_size: 10 }
    })
    if (response.data.success) {
      recentQueries.value = response.data.data.results || response.data.data
    }
  } catch (error) {
    console.error('获取最近查询失败:', error)
  }
}

const fetchRecentBackups = async () => {
  try {
    const response = await api.get('/database/backups/', {
      params: { page_size: 10 }
    })
    if (response.data.success) {
      recentBackups.value = response.data.data.results || response.data.data
    }
  } catch (error) {
    console.error('获取最近备份失败:', error)
  }
}

const fetchActiveAlerts = async () => {
  try {
    const response = await api.get('/database/alerts/', {
      params: { is_resolved: false, page_size: 10 }
    })
    if (response.data.success) {
      activeAlerts.value = response.data.data.results || response.data.data
    }
  } catch (error) {
    console.error('获取活跃告警失败:', error)
  }
}

const resolveAlert = async (alert: any) => {
  try {
    const response = await api.post(`/database/alerts/${alert.id}/resolve_alert/`)
    if (response.data.success) {
      ElMessage.success('告警已解决')
      await fetchActiveAlerts()
      await fetchStats()
    }
  } catch (error) {
    console.error('解决告警失败:', error)
    ElMessage.error('解决告警失败')
  }
}

const getBackupStatusType = (status: string) => {
  const types: Record<string, string> = {
    'completed': 'success',
    'running': 'warning',
    'failed': 'danger'
  }
  return types[status] || 'info'
}

const getBackupStatusText = (status: string) => {
  const texts: Record<string, string> = {
    'completed': '已完成',
    'running': '备份中',
    'failed': '失败'
  }
  return texts[status] || status
}

const getAlertSeverityType = (severity: string) => {
  const types: Record<string, string> = {
    'low': 'info',
    'medium': 'warning',
    'high': 'danger',
    'critical': 'danger'
  }
  return types[severity] || 'info'
}

const getAlertSeverityText = (severity: string) => {
  const texts: Record<string, string> = {
    'low': '低',
    'medium': '中',
    'high': '高',
    'critical': '严重'
  }
  return texts[severity] || severity
}

// 生命周期
onMounted(() => {
  refreshData()
})
</script>

<style scoped>
.database-management {
  padding: 20px;
}

.page-header {
  margin-bottom: 30px;
}

.page-header h1 {
  margin: 0 0 10px 0;
  color: #303133;
}

.page-header p {
  margin: 0;
  color: #909399;
}

.stats-cards {
  margin-bottom: 30px;
}

.stat-card {
  cursor: default;
}

.stat-content {
  display: flex;
  align-items: center;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;
  background: #409eff;
  color: white;
  font-size: 24px;
}

.stat-icon.backup {
  background: #67c23a;
}

.stat-icon.query {
  background: #e6a23c;
}

.stat-icon.alert {
  background: #f56c6c;
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
  line-height: 1;
}

.stat-label {
  font-size: 14px;
  color: #909399;
  margin-top: 4px;
}

.function-nav {
  margin-bottom: 30px;
}

.nav-card {
  cursor: pointer;
  transition: all 0.3s;
}

.nav-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
}

.nav-content {
  text-align: center;
  padding: 20px;
}

.nav-icon {
  font-size: 48px;
  color: #409eff;
  margin-bottom: 16px;
}

.nav-content h3 {
  margin: 0 0 8px 0;
  color: #303133;
}

.nav-content p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.recent-activity {
  margin-bottom: 30px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
